package orchestration.android.execution.commands;

import orchestration.android.RunExecutionActivity;
import orchestration.android.execution.exceptions.TaskExecutionException;
import orchestration.android.execution.tasks.ActivityTask;
import android.app.Activity;
import android.content.Intent;

/**
 * An {@link AndroidOrchestrationCommand} that manages the result of an {@link Activity}
 * @author  <a href="mailto:car.ferrarini@gmail.com">Carlo Ferrarini</a>
 */
public class ManageActivityResultCommand implements AndroidOrchestrationCommand {

	private int resultCode;
	private Intent data;
	
	
	public ManageActivityResultCommand() {}
	
	
	public ManageActivityResultCommand(int resultCode, Intent data) {
		this.resultCode = resultCode;
		this.data = data;
	}


	@Override
	public void execute(RunExecutionActivity rea) {
		ActivityTask currentTask = (ActivityTask)rea.getCurrentTask();
		currentTask.setResult(data);
		try {
			((ActivityTask)currentTask).manageResult(rea);
		} catch (TaskExecutionException e) {
			rea.handleException(e);
			return;
		}
		if(resultCode==Activity.RESULT_CANCELED && !currentTask.isIgnoreBack()){
			rea.setCurrentCommand(CommandFactory.createCommand(CommandFactory.STOP_EXECUTION));
    	}else if(resultCode==Activity.RESULT_OK || (resultCode==Activity.RESULT_CANCELED && currentTask.isIgnoreBack())){
    		rea.setCurrentCommand(CommandFactory.createCommand(CommandFactory.RESUME_EXECUTION));
    	}else{
    		rea.handleException(new TaskExecutionException("unknown result code "+ resultCode));
    	}
		rea.executeNextCommand();
	}

	@Override
	public int getId() {
		return CommandFactory.MANAGE_ACTIVITY_RESULT;
	}

	/**
	 * @param resultCode
	 * @uml.property  name="resultCode"
	 */
	public void setResultCode(int resultCode) {
		this.resultCode = resultCode;
	}

	/**
	 * @param data
	 * @uml.property  name="data"
	 */
	public void setData(Intent data) {
		this.data = data;
	}

	
}
